// 健康管理模块 JavaScript 功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化健康档案页面选项卡功能
    initProfileTabs();
    
    // 初始化病史记录功能
    initMedicalHistory();
    
    // 初始化体检报告功能
    initExaminationReports();
    
    // 初始化疫苗接种记录功能
    initVaccinationRecords();
    
    // 初始化家族病史功能
    initFamilyHistory();
    
    // 初始化健康监测图表
    initHealthMonitoring();
    
    // 绑定健康监测相关事件
    bindMonitoringEvents();
});

// 健康档案选项卡功能
function initProfileTabs() {
    const tabs = document.querySelectorAll('.profile-tabs .tab');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有选项卡的激活状态
            tabs.forEach(t => t.classList.remove('active'));
            
            // 添加当前选项卡的激活状态
            this.classList.add('active');
            
            // 获取目标内容ID
            const targetId = this.getAttribute('data-tab');
            
            // 隐藏所有内容
            tabContents.forEach(content => {
                content.style.display = 'none';
            });
            
            // 显示目标内容
            document.getElementById(targetId).style.display = 'block';
        });
    });
    
    // 绑定保存个人信息按钮事件
    const saveProfileBtn = document.getElementById('save-profile');
    if (saveProfileBtn) {
        saveProfileBtn.addEventListener('click', function() {
            // 模拟保存个人信息
            const formData = {
                name: document.getElementById('name').value,
                gender: document.getElementById('gender').value,
                birthdate: document.getElementById('birthdate').value,
                height: document.getElementById('height').value,
                weight: document.getElementById('weight').value,
                bloodType: document.getElementById('blood-type').value,
                allergies: document.getElementById('allergies').value,
                emergencyContact: document.getElementById('emergency-contact').value
            };
            
            // 这里可以添加表单验证逻辑
            
            // 模拟API请求
            setTimeout(() => {
                alert('个人信息保存成功！');
                console.log('保存的个人信息：', formData);
            }, 500);
        });
    }
}

// 病史记录功能
function initMedicalHistory() {
    // 模拟病史数据
    const medicalRecords = [
        {
            id: 1,
            title: '感冒',
            date: '2023-05-15',
            doctor: '王医生',
            hospital: '健康医院',
            description: '症状：发热、咳嗽、流涕。处方：布洛芬、感冒灵颗粒。'
        },
        {
            id: 2,
            title: '季节性过敏',
            date: '2023-03-22',
            doctor: '李医生',
            hospital: '健康医院',
            description: '症状：皮肤瘙痒、打喷嚏。处方：氯雷他定片、皮炎平软膏。'
        }
    ];
    
    // 渲染病史记录
    renderMedicalRecords(medicalRecords);
    
    // 绑定添加病史记录按钮事件
    const addRecordBtn = document.getElementById('add-medical-record');
    if (addRecordBtn) {
        addRecordBtn.addEventListener('click', function() {
            // 这里可以打开一个模态框来添加病史记录
            // 简化起见，我们直接使用 prompt
            const title = prompt('请输入疾病名称：');
            if (title) {
                const description = prompt('请输入详细描述：');
                if (description) {
                    // 创建新记录
                    const newRecord = {
                        id: medicalRecords.length + 1,
                        title: title,
                        date: new Date().toISOString().split('T')[0],
                        doctor: '自行记录',
                        hospital: '无',
                        description: description
                    };
                    
                    // 添加到记录列表
                    medicalRecords.push(newRecord);
                    
                    // 重新渲染
                    renderMedicalRecords(medicalRecords);
                }
            }
        });
    }
}

// 渲染病史记录
function renderMedicalRecords(records) {
    const container = document.getElementById('medical-records-list');
    if (!container) return;
    
    container.innerHTML = '';
    
    if (records.length === 0) {
        container.innerHTML = '<div class="empty-state">暂无病史记录</div>';
        return;
    }
    
    records.forEach(record => {
        const recordElement = document.createElement('div');
        recordElement.className = 'record-item';
        recordElement.innerHTML = `
            <div class="record-header">
                <span class="record-title">${record.title}</span>
                <span class="record-date">${record.date}</span>
            </div>
            <div class="record-content">
                <p><strong>医生：</strong>${record.doctor}</p>
                <p><strong>医院：</strong>${record.hospital}</p>
                <p><strong>描述：</strong>${record.description}</p>
            </div>
        `;
        container.appendChild(recordElement);
    });
}

// 体检报告功能
function initExaminationReports() {
    // 模拟体检报告数据
    const reports = [
        {
            id: 1,
            title: '年度体检报告',
            date: '2023-06-10',
            hospital: '健康医院',
            year: 2023,
            fileUrl: '#',
            summary: '总体健康状况良好，血压、血糖正常，建议增加运动量。'
        },
        {
            id: 2,
            title: '专项体检报告',
            date: '2022-11-15',
            hospital: '专科医院',
            year: 2022,
            fileUrl: '#',
            summary: '心电图、肝功能等指标正常，无异常发现。'
        }
    ];
    
    // 渲染体检报告
    renderExaminationReports(reports);
    
    // 绑定上传报告按钮事件
    const uploadBtn = document.getElementById('upload-report');
    if (uploadBtn) {
        uploadBtn.addEventListener('click', function() {
            alert('上传功能正在开发中...');
        });
    }
    
    // 绑定年份筛选事件
    const yearFilter = document.getElementById('report-year-filter');
    if (yearFilter) {
        yearFilter.addEventListener('change', function() {
            const selectedYear = this.value;
            let filteredReports;
            
            if (selectedYear === 'all') {
                filteredReports = reports;
            } else {
                filteredReports = reports.filter(report => report.year.toString() === selectedYear);
            }
            
            renderExaminationReports(filteredReports);
        });
    }
}

// 渲染体检报告
function renderExaminationReports(reports) {
    const container = document.getElementById('examination-reports-list');
    if (!container) return;
    
    container.innerHTML = '';
    
    if (reports.length === 0) {
        container.innerHTML = '<div class="empty-state">暂无体检报告</div>';
        return;
    }
    
    reports.forEach(report => {
        const reportElement = document.createElement('div');
        reportElement.className = 'record-item';
        reportElement.innerHTML = `
            <div class="record-header">
                <span class="record-title">${report.title}</span>
                <span class="record-date">${report.date}</span>
            </div>
            <div class="record-content">
                <p><strong>医院：</strong>${report.hospital}</p>
                <p><strong>摘要：</strong>${report.summary}</p>
                <a href="${report.fileUrl}" class="btn btn-primary" style="margin-top: 10px;">查看详情</a>
            </div>
        `;
        container.appendChild(reportElement);
    });
}

// 疫苗接种记录功能
function initVaccinationRecords() {
    // 模拟疫苗接种数据
    const vaccinations = [
        {
            id: 1,
            name: '新冠疫苗（第一剂）',
            date: '2023-01-10',
            location: '社区卫生服务中心',
            manufacturer: '科兴生物',
            batchNumber: 'SZ20230110-001'
        },
        {
            id: 2,
            name: '新冠疫苗（第二剂）',
            date: '2023-02-07',
            location: '社区卫生服务中心',
            manufacturer: '科兴生物',
            batchNumber: 'SZ20230207-002'
        },
        {
            id: 3,
            name: '流感疫苗',
            date: '2022-10-15',
            location: '健康医院',
            manufacturer: '葛兰素史克',
            batchNumber: 'GSK20221015-003'
        }
    ];
    
    // 渲染疫苗接种记录
    renderVaccinationRecords(vaccinations);
    
    // 绑定添加疫苗记录按钮事件
    const addVaccinationBtn = document.getElementById('add-vaccination');
    if (addVaccinationBtn) {
        addVaccinationBtn.addEventListener('click', function() {
            alert('添加疫苗接种记录功能正在开发中...');
        });
    }
}

// 渲染疫苗接种记录
function renderVaccinationRecords(vaccinations) {
    const container = document.getElementById('vaccination-records');
    if (!container) return;
    
    container.innerHTML = '';
    
    if (vaccinations.length === 0) {
        container.innerHTML = '<div class="empty-state">暂无疫苗接种记录</div>';
        return;
    }
    
    // 按日期排序（从新到旧）
    vaccinations.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    vaccinations.forEach(vaccination => {
        const item = document.createElement('div');
        item.className = 'timeline-item';
        
        const date = new Date(vaccination.date);
        const formattedDate = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
        
        item.innerHTML = `
            <div class="timeline-date">${formattedDate}</div>
            <div class="timeline-content">
                <h4>${vaccination.name}</h4>
                <p><strong>接种地点：</strong>${vaccination.location}</p>
                <p><strong>疫苗厂商：</strong>${vaccination.manufacturer}</p>
                <p><strong>批次号：</strong>${vaccination.batchNumber}</p>
            </div>
        `;
        
        container.appendChild(item);
    });
}

// 家族病史功能
function initFamilyHistory() {
    // 模拟家族病史数据
    const familyHistory = [
        { relation: 'father', disease: '高血压' },
        { relation: 'grandmother-paternal', disease: '2型糖尿病' }
    ];
    
    // 绑定添加家族病史按钮事件
    const addFamilyHistoryBtn = document.getElementById('add-family-history');
    if (addFamilyHistoryBtn) {
        addFamilyHistoryBtn.addEventListener('click', function() {
            const relation = document.getElementById('relation').value;
            const disease = document.getElementById('disease').value;
            
            if (disease.trim() === '') {
                alert('请输入疾病名称');
                return;
            }
            
            // 添加到家族病史
            familyHistory.push({ relation, disease });
            
            // 重新渲染家族病史图
            renderFamilyHistoryTree(familyHistory);
            
            // 清空输入框
            document.getElementById('disease').value = '';
            
            alert('家族病史添加成功！');
        });
    }
    
    // 初始渲染家族病史图
    renderFamilyHistoryTree(familyHistory);
}

// 渲染家族病史图
function renderFamilyHistoryTree(familyHistory) {
    const container = document.getElementById('family-tree-chart');
    if (!container) return;
    
    // 在实际项目中，这里可以使用专业的家谱图库来绘制
    // 这里简化为文本展示
    
    container.innerHTML = '<h3>家族病史记录</h3>';
    
    if (familyHistory.length === 0) {
        container.innerHTML += '<p>暂无家族病史记录</p>';
        return;
    }
    
    const relationMap = {
        'father': '父亲',
        'mother': '母亲',
        'grandfather-paternal': '祖父',
        'grandmother-paternal': '祖母',
        'grandfather-maternal': '外祖父',
        'grandmother-maternal': '外祖母'
    };
    
    const list = document.createElement('ul');
    list.className = 'family-history-list';
    
    familyHistory.forEach(item => {
        const listItem = document.createElement('li');
        listItem.textContent = `${relationMap[item.relation] || item.relation}：${item.disease}`;
        list.appendChild(listItem);
    });
    
    container.appendChild(list);
}

// 健康监测功能
function initHealthMonitoring() {
    // 初始化图表
    initHeartRateChart();
    initBloodOxygenChart();
    initBloodPressureChart();
    initStepsChart();
    initHealthTrendChart();
    
    // 初始化手动记录功能
    initManualRecording();
}

// 初始化心率图表
function initHeartRateChart() {
    const ctx = document.getElementById('heart-rate-chart');
    if (!ctx) return;
    
    // 模拟心率数据
    const labels = Array.from({length: 24}, (_, i) => `${i}:00`);
    const data = [72, 70, 68, 65, 64, 63, 65, 68, 72, 75, 78, 80, 82, 85, 83, 80, 78, 76, 75, 74, 73, 72, 71, 70];
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '心率',
                data: data,
                borderColor: '#ff6384',
                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 50,
                    max: 100
                }
            }
        }
    });
}

// 初始化血氧图表
function initBloodOxygenChart() {
    const ctx = document.getElementById('blood-oxygen-chart');
    if (!ctx) return;
    
    // 模拟血氧数据
    const labels = Array.from({length: 24}, (_, i) => `${i}:00`);
    const data = [98, 98, 97, 97, 97, 96, 97, 97, 98, 98, 99, 99, 98, 98, 98, 97, 97, 98, 98, 98, 97, 97, 98, 98];
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '血氧',
                data: data,
                borderColor: '#36a2eb',
                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 90,
                    max: 100
                }
            }
        }
    });
}

// 初始化血压图表
function initBloodPressureChart() {
    const ctx = document.getElementById('blood-pressure-chart');
    if (!ctx) return;
    
    // 模拟血压数据
    const labels = ['早晨', '中午', '晚上'];
    const systolicData = [125, 128, 122];
    const diastolicData = [80, 82, 78];
    
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '收缩压',
                    data: systolicData,
                    backgroundColor: 'rgba(255, 99, 132, 0.7)',
                    borderWidth: 0
                },
                {
                    label: '舒张压',
                    data: diastolicData,
                    backgroundColor: 'rgba(54, 162, 235, 0.7)',
                    borderWidth: 0
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 50,
                    max: 150
                }
            }
        }
    });
}

// 初始化步数图表
function initStepsChart() {
    const ctx = document.getElementById('steps-chart');
    if (!ctx) return;
    
    // 模拟步数数据
    const labels = Array.from({length: 7}, (_, i) => {
        const d = new Date();
        d.setDate(d.getDate() - 6 + i);
        return d.toLocaleDateString('zh-CN', {weekday: 'short'});
    });
    
    const data = [5230, 7845, 8465, 6782, 9120, 7650, 8465];
    
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '步数',
                data: data,
                backgroundColor: 'rgba(75, 192, 192, 0.7)',
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 初始化健康趋势图表
function initHealthTrendChart() {
    const ctx = document.getElementById('health-trend-chart');
    if (!ctx) return;
    
    // 模拟周数据
    const weekLabels = Array.from({length: 7}, (_, i) => {
        const d = new Date();
        d.setDate(d.getDate() - 6 + i);
        return d.toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'});
    });
    
    // 模拟体重数据
    const weightData = [68.5, 68.3, 68.2, 68.0, 67.8, 67.7, 67.5];
    
    // 初始化图表
    const healthTrendChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: weekLabels,
            datasets: [{
                label: '体重 (kg)',
                data: weightData,
                borderColor: '#4bc0c0',
                backgroundColor: 'rgba(75, 192, 192, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '体重趋势'
                }
            }
        }
    });
    
    // 存储图表实例以便后续更新
    window.healthTrendChart = healthTrendChart;
}

// 绑定健康监测相关事件
function bindMonitoringEvents() {
    // 绑定刷新数据按钮
    const refreshBtn = document.getElementById('refresh-data');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            // 模拟数据刷新
            document.getElementById('heart-rate-value').innerHTML = Math.floor(70 + Math.random() * 10) + ' <small>次/分</small>';
            document.getElementById('blood-oxygen-value').innerHTML = Math.floor(96 + Math.random() * 4) + ' <small>%</small>';
            document.getElementById('blood-pressure-value').innerHTML = Math.floor(115 + Math.random() * 10) + '/' + Math.floor(75 + Math.random() * 10) + ' <small>mmHg</small>';
            document.getElementById('steps-value').innerHTML = Math.floor(8000 + Math.random() * 1000).toLocaleString() + ' <small>步</small>';
            
            alert('数据已刷新！');
        });
    }
    
    // 绑定查看历史按钮
    const historyBtn = document.getElementById('view-history');
    if (historyBtn) {
        historyBtn.addEventListener('click', function() {
            alert('历史数据查看功能正在开发中...');
        });
    }
    
    // 绑定周期选择按钮
    const periodBtns = document.querySelectorAll('.period-btn');
    periodBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除所有按钮的激活状态
            periodBtns.forEach(b => b.classList.remove('active'));
            
            // 添加当前按钮的激活状态
            this.classList.add('active');
            
            // 获取选择的周期
            const period = this.getAttribute('data-period');
            
            // 更新健康趋势图表
            updateHealthTrendChart(period);
        });
    });
}

// 更新健康趋势图表
function updateHealthTrendChart(period) {
    if (!window.healthTrendChart) return;
    
    let labels, data, title;
    
    // 根据周期生成不同的数据
    switch (period) {
        case 'week':
            labels = Array.from({length: 7}, (_, i) => {
                const d = new Date();
                d.setDate(d.getDate() - 6 + i);
                return d.toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'});
            });
            data = [68.5, 68.3, 68.2, 68.0, 67.8, 67.7, 67.5];
            title = '体重趋势（周）';
            break;
            
        case 'month':
            labels = Array.from({length: 30}, (_, i) => {
                const d = new Date();
                d.setDate(d.getDate() - 29 + i);
                return d.toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'});
            });
            // 生成30天的模拟数据
            data = Array.from({length: 30}, (_, i) => {
                return (69 - i * 0.05).toFixed(1);
            });
            title = '体重趋势（月）';
            break;
            
        case 'year':
            labels = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
            data = [70.5, 70.2, 69.8, 69.5, 69.0, 68.7, 68.5, 68.2, 68.0, 67.8, 67.5, 67.2];
            title = '体重趋势（年）';
            break;
    }
    
    // 更新图表数据
    window.healthTrendChart.data.labels = labels;
    window.healthTrendChart.data.datasets[0].data = data;
    window.healthTrendChart.options.plugins.title.text = title;
    window.healthTrendChart.update();
}

// 初始化手动记录功能
function initManualRecording() {
    const saveRecordBtn = document.getElementById('save-record');
    if (!saveRecordBtn) return;
    
    // 设置默认日期时间为当前时间
    const datetimeInput = document.getElementById('record-datetime');
    if (datetimeInput) {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        
        datetimeInput.value = `${year}-${month}-${day}T${hours}:${minutes}`;
    }
    
    // 绑定记录类型变化事件，动态更新单位
    const recordTypeSelect = document.getElementById('record-type');
    const recordValueInput = document.getElementById('record-value');
    
    if (recordTypeSelect && recordValueInput) {
        recordTypeSelect.addEventListener('change', function() {
            const type = this.value;
            let placeholder = '';
            
            switch (type) {
                case 'weight':
                    placeholder = '单位：kg（例如：67.5）';
                    break;
                case 'blood-sugar':
                    placeholder = '单位：mmol/L（例如：5.6）';
                    break;
                case 'temperature':
                    placeholder = '单位：°C（例如：36.5）';
                    break;
                case 'sleep':
                    placeholder = '单位：小时（例如：7.5）';
                    break;
            }
            
            recordValueInput.placeholder = placeholder;
        });
        
        // 触发一次change事件以设置初始placeholder
        recordTypeSelect.dispatchEvent(new Event('change'));
    }
    
    // 绑定保存记录按钮事件
    saveRecordBtn.addEventListener('click', function() {
        const type = document.getElementById('record-type').value;
        const value = document.getElementById('record-value').value;
        const datetime = document.getElementById('record-datetime').value;
        
        if (!value) {
            alert('请输入数值');
            return;
        }
        
        // 模拟保存记录
        const record = {
            type,
            value,
            datetime
        };
        
        console.log('保存的健康记录：', record);
        
        // 根据记录类型更新对应的图表
        switch (type) {
            case 'weight':
                // 更新体重趋势图
                if (window.healthTrendChart) {
                    const data = [...window.healthTrendChart.data.datasets[0].data];
                    data.push(parseFloat(value));
                    data.shift(); // 移除最早的一个数据点
                    window.healthTrendChart.data.datasets[0].data = data;
                    window.healthTrendChart.update();
                }
                break;
        }
        
        alert('记录保存成功！');
        
        // 清空输入框
        document.getElementById('record-value').value = '';
    });
} 